/* svnNotifierClient.c
 *
 * Simple test app for the daemon. This tests the remote connectivity as
 * the client will be able to test the local connectivity.
 */

#include <stdio.h>
#include <stdlib.h>

#include "apr_pools.h"
#include "apr_network_io.h"
#include "apr_poll.h"
#include "apr_errno.h"
#include "apr_strings.h"

#include "svnNotifier.h"

static apr_pool_t *clientPool = NULL;

static void usage(void)
{
    fprintf(stderr, "svnNotifierClient <repo> <rev>\n");
    exit(1);
}

/* Invoked as 
 * svnNotifierClient <repo> <rev>
 */
int main(int argc, char **argv)
{
    apr_status_t rv = 1;
    apr_sockaddr_t *them = NULL;
    apr_socket_t *sock = NULL;
    char *data = NULL;

    if (argc < 3)
        usage();

    apr_initialize();
    if (apr_pool_create(&clientPool, NULL) != APR_SUCCESS) {
        fprintf(stderr, "Unable to create a pool\n");
        exit(1);
    }

    rv = apr_sockaddr_info_get(&them, "127.0.0.1", APR_UNSPEC,
                               SVN_NOTIFY_LOCAL, 0, clientPool);
    data = apr_psprintf(clientPool, "<?xml version=\"1.0\"?><update><repos>%s"
                        "</repos><rev>%s</rev></update>", argv[1], argv[2]);

    rv = apr_socket_create(&sock, them->family, SOCK_STREAM, 0, clientPool);

    rv = apr_socket_connect(sock, them);
    if (rv != APR_SUCCESS)
        fprintf(stderr, "Failed to connect to svnNotifier daemon\n");
    else {
        apr_size_t bytesSent = strlen(data);
        rv = apr_socket_send(sock, data, &bytesSent);
        if (rv != APR_SUCCESS || bytesSent != strlen(data))
            fprintf(stderr, "Failed to send the data correctly\n");
    }
    
    apr_socket_close(sock);
    apr_pool_destroy(clientPool);

    return (0);
}
